//
//  PTReadContact.swift
//  PTWatch Watch App
//
//  Created by sc-chen on 2023/9/20.
//

import SwiftUI
import Contacts

struct PTReadContact: View {
    @State private var isContactsAuthorized = true
    @State private var isShowingHUD = false
    @State private var detailTxt = "不支持开发功能"
    
    @State private var pt_contacts = [PTContact]()
    
    var body: some View {
        ZStack {
            VStack {
                Button {
                    if isContactsAuthorized {
                        fetchContacts()
                    }else{
                        requestContactsAccess()
                    }
                } label: {
                    Text("读取电话本数据")
                        .font(.system(size: 13))
                        .padding(EdgeInsets(top: 10, leading: 30, bottom: 10, trailing: 30))
                        .foregroundColor(.blue)
                        .overlay(
                            RoundedRectangle(cornerRadius: 10)
                                .stroke(Color.blue, lineWidth: 1)
                                .padding(.trailing,5)
                        )
                }
                .buttonStyle(.plain)
                .padding()
                List(pt_contacts, id: \.self) { contact in
                    NavigationLink(destination: PTContactDetail(contact: contact)) {
                        VStack(alignment: .leading) {
                            Text("\(contact.name)")
                        }
                    }
                }
                .navigationBarTitleDisplayMode(.inline)
            }
            PTProgressHud(isPresented: $isShowingHUD, text: $detailTxt)
        }
    }
    
    private func fetchContacts() {
        let store = CNContactStore()
        let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey,CNContactImageDataKey] as [CNKeyDescriptor]
        let request = CNContactFetchRequest(keysToFetch: keys)
        
        DispatchQueue.global().async {
            do {
                try store.enumerateContacts(with: request) { contact, stop in
                    let con = makePTContact(contact: contact)
                    pt_contacts.append(con)
                }
            } catch {
                print("Error fetching contacts: \(error.localizedDescription)")
            }
        }
    }
    
    private func requestContactsAccess() {
        let store = CNContactStore()
        store.requestAccess(for: .contacts) { granted, error in
            DispatchQueue.main.async {
                isContactsAuthorized = granted
                if !granted {
                    detailTxt = "请在设置中打开通讯录权限!"
                    showHud()
                }else{
                    fetchContacts()
                }
            }
        }
    }
    
    func makePTContact(contact: CNContact) -> PTContact {
        let userIconData = contact.imageData
        var name = "\(contact.givenName) \(contact.familyName)"
        var mobile = "";
        for number in contact.phoneNumbers{
            if !number.value.stringValue.isEmpty {
                mobile = number.value.stringValue
                if name==" " {
                    name = mobile
                }
                break
            }
        }
        return PTContact.init(icon: userIconData, name: name, number: mobile)
    }
    
    private func showHud() {
        isShowingHUD = true
        DispatchQueue.main.asyncAfter(deadline: .now()+2){
            isShowingHUD = false
        }
    }
}

struct PTReadContact_Previews: PreviewProvider {
    static var previews: some View {
        PTReadContact()
    }
}
